from django.db import models
from django.utils import timezone
import os


class RepairRecord(models.Model):
    """
    设备维修记录单模型
    """
    # 基本信息
    record_number = models.CharField(max_length=50, verbose_name='记录编号', unique=True, blank=True, null=True)
    system_name = models.CharField(max_length=200, verbose_name='系统名称')
    equipment_name = models.CharField(max_length=200, verbose_name='设备名称')
    equipment_number = models.CharField(max_length=100, verbose_name='设备编号', blank=True)
    
    # 故障信息
    fault_date = models.DateField(verbose_name='故障日期', null=True, blank=True)
    fault_description = models.TextField(verbose_name='故障描述', blank=True)
    
    # 维修信息
    maintainer_name = models.CharField(max_length=100, verbose_name='维修厂家名称', blank=True)
    contact_phone = models.CharField(max_length=50, verbose_name='厂家联系人及电话', blank=True)
    maintenance_method = models.TextField(verbose_name='维修方法', blank=True)
    replacement_parts = models.TextField(verbose_name='更换备件', blank=True)
    
    # 完成信息
    completion_date = models.DateField(verbose_name='完成日期', null=True, blank=True)
    confirmer = models.CharField(max_length=100, verbose_name='确认人', blank=True)
    attachments = models.TextField(verbose_name='附图', blank=True)
    
    # 系统字段
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'equipment_repair_record'
        verbose_name = '设备维修记录单'
        verbose_name_plural = '设备维修记录单'
        ordering = ['-create_time']
    
    def __str__(self):
        return f'{self.record_number} - {self.system_name} - {self.equipment_name}'


class MaintenanceItem(models.Model):
    """
    设备维护维保记录表模型（包含维保内容）
    """
    
    SYSTEM_CATEGORY_CHOICES = [
        ('真空热试验系统维护保养记录表', '真空热试验系统维护保养记录表'),
        ('振动试验系统维护保养记录表', '振动试验系统维护保养记录表'),
        ('EMC试验系统维护保养记录表', 'EMC试验系统维护保养记录表'),
        ('磁试验系统维护保养记录表', '磁试验系统维护保养记录表'),
        ('常压试验系统维护保养记录表', '常压试验系统维护保养记录表'),
    ]
    
    # 系统信息
    system_name = models.CharField(max_length=200, verbose_name='系统名称')
    system_category = models.CharField(
        max_length=100, 
        verbose_name='系统分类',
        default='真空热试验系统维护保养记录表'
    )
    
    # 设备和维保信息
    equipment_name = models.CharField(max_length=200, verbose_name='设备名称')
    content = models.CharField(max_length=500, verbose_name='维保内容')
    level = models.CharField(max_length=50, verbose_name='级别', blank=True)
    cycle = models.CharField(max_length=50, verbose_name='周期', blank=True)
    type = models.CharField(max_length=50, verbose_name='类型', blank=True)
    
    # 12个月的维保记录
    january = models.CharField(max_length=200, verbose_name='1月', blank=True)
    february = models.CharField(max_length=200, verbose_name='2月', blank=True)
    march = models.CharField(max_length=200, verbose_name='3月', blank=True)
    april = models.CharField(max_length=200, verbose_name='4月', blank=True)
    may = models.CharField(max_length=200, verbose_name='5月', blank=True)
    june = models.CharField(max_length=200, verbose_name='6月', blank=True)
    july = models.CharField(max_length=200, verbose_name='7月', blank=True)
    august = models.CharField(max_length=200, verbose_name='8月', blank=True)
    september = models.CharField(max_length=200, verbose_name='9月', blank=True)
    october = models.CharField(max_length=200, verbose_name='10月', blank=True)
    november = models.CharField(max_length=200, verbose_name='11月', blank=True)
    december = models.CharField(max_length=200, verbose_name='12月', blank=True)
    
    # 系统字段
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'equipment_maintenance_item'
        verbose_name = '设备维护维保记录表'
        verbose_name_plural = '设备维护维保记录表'
        ordering = ['-create_time']
    
    def __str__(self):
        return f'{self.system_name} - {self.equipment_name} - {self.content}'


def repair_image_upload_path(instance, filename):
    """
    生成维修记录图片的上传路径
    """
    # 获取文件扩展名
    ext = filename.split('.')[-1]
    # 生成新的文件名：维修记录ID_时间戳.扩展名
    new_filename = f"{instance.repair_record.id}_{timezone.now().strftime('%Y%m%d_%H%M%S')}.{ext}"
    # 返回完整路径：repair_images/年份/月份/文件名
    return os.path.join('repair_images', timezone.now().strftime('%Y'), timezone.now().strftime('%m'), new_filename)


class RepairRecordImage(models.Model):
    """
    维修记录附图模型
    """
    repair_record = models.ForeignKey(
        RepairRecord, 
        on_delete=models.CASCADE, 
        related_name='images',
        verbose_name='维修记录'
    )
    image = models.ImageField(
        upload_to=repair_image_upload_path,
        verbose_name='图片文件',
        help_text='支持jpg、png、gif等格式'
    )
    original_filename = models.CharField(
        max_length=255, 
        verbose_name='原始文件名',
        help_text='用户上传时的原始文件名'
    )
    file_size = models.PositiveIntegerField(
        verbose_name='文件大小（字节）',
        null=True,
        blank=True
    )
    description = models.CharField(
        max_length=500, 
        verbose_name='图片描述',
        blank=True,
        help_text='可选的图片说明'
    )
    upload_time = models.DateTimeField(
        auto_now_add=True, 
        verbose_name='上传时间'
    )
    
    class Meta:
        db_table = 'equipment_repair_record_image'
        verbose_name = '维修记录附图'
        verbose_name_plural = '维修记录附图'
        ordering = ['-upload_time']
    
    def __str__(self):
        return f'{self.repair_record.record_number} - {self.original_filename}'
    
    def save(self, *args, **kwargs):
        """
        保存时自动设置文件大小
        """
        if self.image and not self.file_size:
            self.file_size = self.image.size
        super().save(*args, **kwargs)
    
    def delete(self, *args, **kwargs):
        """
        删除模型实例时同时删除文件
        """
        if self.image:
            if os.path.isfile(self.image.path):
                os.remove(self.image.path)
        super().delete(*args, **kwargs)
    
    @property
    def file_size_human_readable(self):
        """
        返回人类可读的文件大小
        """
        if not self.file_size:
            return '未知'
        
        for unit in ['B', 'KB', 'MB', 'GB']:
            if self.file_size < 1024.0:
                return f"{self.file_size:.1f} {unit}"
            self.file_size /= 1024.0
        return f"{self.file_size:.1f} TB"
